package org.rbreznak.tronco.client;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JPanel;

public class KeyboardPanel extends JPanel implements ActionListener {
	private ArrayList<JButton> keys = new ArrayList<JButton>();
    private List<KeyListener> _listeners = new ArrayList<KeyListener>();
    
    private String data = "";
    
	public KeyboardPanel() {
		setLayout(new GraphPaperLayout(new Dimension(10, 5), 5, 5));
		setBackground(new Color(0,0,0));
		
		// 0 - 9
		for(int i = 0;i<10;i++) {
			keys.add(new JButton(Character.toString((char) (48 + i) )));
			add(keys.get(i),  new Rectangle(i, 0, 1, 1));
			FormatUI.formatButton(keys.get(i));
			keys.get(i).setSelected(false);
			keys.get(i).addActionListener(this);
		}
		
		// A - Z
		for(int i = 10;i<35;i++) {
			keys.add(new JButton(Character.toString((char) (55 + i) )));
			add(keys.get(i), new Rectangle(i%10,(int)(i/10), 1, 1));
			FormatUI.formatButton(keys.get(i));
			keys.get(i).setSelected(false);
			keys.get(i).addActionListener(this);
		}
		
		keys.add(new JButton(Character.toString(' ')));
		add(keys.get(35), new Rectangle(0, 4, 10, 1));
		FormatUI.formatButton(keys.get(35));
		keys.get(35).setSelected(false);
		keys.get(35).addActionListener(this);
	}
	
	public String getData() {
		return data;
	}

	public void actionPerformed(ActionEvent e) {
		fire(((JButton) e.getSource()).getText().charAt(0)); 
	}
	
    public synchronized void addKeyListener( KeyListener l ) {
        _listeners.add( l );
    }
    
    public synchronized void removeKeyListener( KeyListener l ) {
        _listeners.remove( l );
    }
    
    public synchronized void removeAllButOneKeyListener(KeyListener l ) {
    	_listeners.clear();
    	addKeyListener(l);
    }
    
    protected synchronized void fire(char c) {
    	KeyEvent evnt = new KeyEvent(this, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, c, c);
    	((KeyEvent) evnt).setKeyChar(c);
        Iterator listeners = _listeners.iterator();
        while( listeners.hasNext() ) {
            ( (KeyListener) listeners.next() ).keyTyped( (KeyEvent) evnt );
        }
    }    
}
